from rest_framework import serializers
from user.models import User


class UserSerialzier(serializers.ModelSerializer):
    allow = serializers.CharField(write_only=True)
    password1 = serializers.CharField(max_length=20, min_length=8, write_only=True)

    class Meta:
        model = User
        fields = '__all__'

    extra_kwargs = {
        'username': {
            'max_length': 20,
            'min_length': 5
        },
        'password': {
            'max_length': 20,
            'min_length': 8,
            'write_only': True
        },
    }

    def validate(self, attrs):
        """
            多字段验证
        """

        if attrs['password'] != attrs['password1']:
            raise serializers.ValidationError('密码不一致')

        return attrs

    def create(self, validated_data):
        user = User.objects.create_user(username=validated_data['username'], password=validated_data['password'],
                                        email=validated_data['email'])
        return user


class UserSerialzier1(serializers.Serializer):
    user_name = serializers.CharField(max_length=20, min_length=5)
    pwd = serializers.CharField(max_length=20, min_length=8)
    cpwd = serializers.CharField(max_length=20, min_length=8)
    email = serializers.EmailField()
    allow = serializers.CharField(write_only=True)

    def validate(self, attrs):
        """
            多字段验证
        """

        if attrs['pwd'] != attrs['cpwd']:
            raise serializers.ValidationError('密码不一致')

        if attrs['allow'] != 'on':
            raise serializers.ValidationError('未同意协议')

        return attrs

    def create(self, validated_data):
        user = User.objects.create_user(username=validated_data['user_name'], password=validated_data['pwd'],
                                        email=validated_data['email'])
        return user
